function formatTime(timestamp) {
  var date = new Date(timestamp * 1000);
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function checkMobilePhone(mobilePhone) {
  if ((/^1[34578]\d{9}$/.test(mobilePhone))) {
    return true;
    
  } else {
       my.showToast({
      content: '手机号输入有误', 
      duration:1000
    });
    return false;

  }
}

function checkEmail(email) {
  if ((/^([.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/.test(email))) {
    return true;
  } else {
    return false;
  }
}

function showNotice(msg) {
  my.showToast({
    content: msg
  })
}

/**
 * 手势库
 */
function touchstart(e, _this) {
  const t = e.touches[0],
    startX = t.clientX,
    startY = t.clientY;
  _this.setData({
    'gesture.startX': startX,
    'gesture.startY': startY,
    'gesture.out': true
  })
}
/**
 * 左滑
 * @returns {boolean} 布尔值
 */
function isLeftSlide(e, _this) {
  if (_this.data.gesture.out) {
    const t = e.touches[0],
      deltaX = t.clientX - _this.data.gesture.startX,
      deltaY = t.clientY - _this.data.gesture.startY;

    if (deltaX < -20 && deltaX > -40 && deltaY < 8 && deltaY > -8) {
      _this.setData({
        'gesture.out': false
      })
      return true;
    } else {
      return false;
    }
  }
}
/**
 * 右滑
 * @returns {boolean} 布尔值
 */
function isRightSlide(e, _this) {
  if (_this.data.gesture.out) {
    const t = e.touches[0],
      deltaX = t.clientX - _this.data.gesture.startX,
      deltaY = t.clientY - _this.data.gesture.startY;

    if (deltaX > 20 && deltaX < 40 && deltaY < 8 && deltaY > -8) {
      _this.setData({
        'gesture.out': false
      })
      return true;
    } else {
      return false;
    }
  }
}

function timeHandle(timestamp) {
  var now = Date.parse(new Date()) / 1000;
  var time = now - timestamp;
  if (time < 30) {
    time = '刚刚';
  }
  else if (time < 60) {
    time = time + '秒前'
  } else if (time < 3600) {
    time = parseInt(time / 60) + '分钟前'
  } else if (time < 86400) {
    time = parseInt(time / 3600) + '小时前'
  } else {
    time = parseInt(time / 86400) + '天前'
  }
  return time
}

/*过滤4字节字符*/
function guolv4(str) {
  return str.replace(/([\ud800-\udbff][\u0000-\uffff])/g, '');
}

/*过滤两端空格*/
function trimStr(str) {
  return str.replace(/(^\s*)|(\s*$)/g, "");
}

/*  转同步 */
function wxPromise(fn) {
  return function (obj = {}) {
    console.log(obj)
    return new Promise((resolve, reject) => {
      obj.success = function (res) {
        if (res.status == 500) {
          showNotice('服务器出了点小问题');
          return
        }
        resolve(res)
      }
      obj.fail = function (res) {
        reject(res)
      }
      fn(obj)
    })
  }
}

/*  转同步带检查登录处理 */
function checkLogin(fn, errOperation) {
  // console.log("我执行了")
  return function (obj = {}) {
    return new Promise((resolve, reject) => {
      // console.log("我也执行了")
      // console.log(obj)
      obj.success = function (res) {
        console.log(res)
        // console.log("我也也执行了")
        my.stopPullDownRefresh();
        if (res.headers.Authorization) {
          console.log(res.headers.Authorization);
          my.setStorageSync({
            key: "loginTokenValue",
            data: {
              loginToken: res.headers.Authorization
            }
          });
        }
        if (res.status == 500) {
          showNotice('服务器出了点小问题');
          return
        }
        if (res.status == 200) {
          resolve(res)
        } else if (status == 400) {
          let page = getCurrentPages();
          let length = page.length;
          let app = getApp();
          console.log(page);
          if (length == 1) {
            app.globalData.routeF = 'switchTab';
          } else {
            app.globalData.routeF = 'redirectTo';
          }
          var url = '/' + page[length - 1].route;
          var options = page[length - 1].options;
          if (options != undefined) {
            url += '?';
            for (var key in options) {
              url = url + key + '=' + options[key] + '&';
            }
            url = url.slice(0, -1)
          }
          console.log('url:' + url);
          app.globalData.route = url;
          my.navigateTo({
            url: '/pages/login/login',
          })
          return
        } else {
          if (errOperation) {
            resolve(res)
          } else {
            my.hideLoading();
            my.showToast({
              content: res.data.msg
            })
          }
        }
      }
      obj.fail = function (res) {
        console.log("失败")
        reject(res)
      }
      fn(obj)
    })
  }
}
/* 带登录判断同步请求 */
function PRL(url, data, errOperation = false) {
  var Authorization = my.getStorageSync({ key: 'loginToken' }).data;
  console.log(Authorization)
  var timestamp = (Date.parse(new Date()) / 1000).toString();
  var obj;
  if (Authorization == undefined) {
    obj = {
      url: url,
      method: 'POST',
      dataType: 'json',
      data: data,
      headers: {
        timestamp: timestamp
      }
    }
  } else {
    obj = {
      url: url,
      method: 'POST',
      dataType: 'json',
      data: data,
      headers: {
        Authorization: Authorization,
        timestamp: timestamp
      }
    }
  }
  console.log(obj)
  var postRequest = checkLogin(my.httpRequest, errOperation)
  return postRequest(obj)
}

/* POST同步请求 */
function POST(url, data) {
  var timestamp = (Date.parse(new Date()) / 1000).toString();
  var Authorization = my.getStorageSync({ key: 'loginToken' }).data;
  var postRequest = wxPromise(my.httpRequest)
  return postRequest({
    url: url,
    method: 'POST',
    data: data,
    dataType: 'json',
    headers: {
      timestamp: timestamp,
      Authorization:Authorization
    }
  })
}
/* 带登录信息GET同步请求 */
function GRL(url, data) {
  let res = my.getStorageSync({ key: 'loginToken' });
  console.log(res)
  var Authorization = res.data;
  // console.log(typeof(Authorization));
  var timestamp = (Date.parse(new Date()) / 1000).toString();
  var getRequest = checkLogin(my.httpRequest, false);
  return getRequest({
    url: url,
    method: 'GET',
    data: data,
    headers: {
      Authorization: Authorization,
      timestamp: timestamp
    }
  })
}
function loginPost(url, data) {
  let res = my.getStorageSync({ key: 'loginToken' });
  console.log(res)
  var Authorization = res.data;
  console.log(typeof(Authorization));
  var timestamp = (Date.parse(new Date()) / 1000).toString();
  var getRequest = checkLogin(my.httpRequest, false);
  return getRequest({
    url: url,
    method: 'POST',
    data: data,
    headers: {
      Authorization: Authorization,
      timestamp: timestamp
    }
  })
}

/* 替换字符串中间字符 */
function changeStr(str, start, length, item) {
  var arr = str.split('');
  console.log(arr);
  arr.splice(start, length, item);
  console.log(arr);
  return arr.join('');
}

/* 倒计时 */
function countdown(that, second) {
  var code_time = that.data.code_time;
  var code_disabled = that.data.code_disabled;
  if (second < 0) {
    code_time = '重新获取';
    code_disabled = false;
    that.setData({
      code_time: code_time,
      code_disabled: code_disabled,
      getcode:"getcode"
    });
    return;
  }
  var time = setTimeout(function () {
    code_time = second--;
    that.setData({
      code_time: code_time
    });
    countdown(that, second);
  }, 1000)
}

var Wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1];    // 加权因子  
var ValideCode = [1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2];            // 身份证验证位值.10代表X

function checkIDcard(idCard) {
  if (idCard.length == 18) {
    var a_idCard = idCard.split("");                // 得到身份证数组     
    if (isValidityBrithBy18IdCard(idCard) && isTrueValidateCodeBy18IdCard(a_idCard)) {   //进行18位身份证的基本验证和第18位的验证  
      return true;
    } else {
      return false;
    }
  } else {
    return false;
  }
}

/**   
     * 判断身份证号码为18位时最后的验证位是否正确   
     * @param a_idCard 身份证号码数组   
     * @return   
     */
function isTrueValidateCodeBy18IdCard(a_idCard) {
  var sum = 0;                             // 声明加权求和变量     
  if (a_idCard[17].toLowerCase() == 'x') {
    a_idCard[17] = 10;                    // 将最后位为x的验证码替换为10方便后续操作     
  }
  for (var i = 0; i < 17; i++) {
    sum += Wi[i] * a_idCard[i];            // 加权求和     
  }
  var valCodePosition = sum % 11;                // 得到验证码所位置     
  if (a_idCard[17] == ValideCode[valCodePosition]) {
    return true;
  } else {
    return false;
  }
}
/**   
  * 验证18位数身份证号码中的生日是否是有效生日   
  * @param idCard 18位书身份证字符串   
  * @return   
  */
function isValidityBrithBy18IdCard(idCard18) {
  var year = idCard18.substring(6, 10);
  var month = idCard18.substring(10, 12);
  var day = idCard18.substring(12, 14);
  var temp_date = new Date(year, parseFloat(month) - 1, parseFloat(day));
  // 这里用getFullYear()获取年份，避免千年虫问题     
  if (temp_date.getFullYear() != parseFloat(year)
    || temp_date.getMonth() != parseFloat(month) - 1
    || temp_date.getDate() != parseFloat(day)) {
    return false;
  } else {
    return true;
  }
}

function encrypt(str) {
  let arr = str.split("");
  arr.splice();
  arr.splice(3, 4, '****');
  str = arr.join('')
  return str;
}

function confirm(content, confirmText = '确定') {
  return new Promise((resolve, reject) => {
    my.confirm({
      title: '提示',
      content: content,
      confirmText: confirmText,
      success: res => {
        if (res.confirm) {
          resolve()
        } else if (res.cancel) {
          reject()
        }
      }
    })
  })
}


module.exports = {
  formatTime: formatTime,
  checkMobilePhone: checkMobilePhone,
  checkEmail: checkEmail,
  checkIDcard: checkIDcard,
  showNotice: showNotice,
  confirm: confirm,
  timeHandle: timeHandle,
  guolv4: guolv4,
  trimStr: trimStr,
  wxPromise: wxPromise,
  changeStr: changeStr,
  countdown, countdown,
  PRL: PRL,
  POST: POST,
  GRL: GRL,
  gesture: {
    touchstart: touchstart,
    isLeftSlide: isLeftSlide,
    isRightSlide: isRightSlide
  },
  encrypt: encrypt
}
